package a02_链表;

/**
 * <p>
 * a02_设计链表
 * </p>
 *
 * @author flyduck
 * @since 2024-06-14
 */
public class a03_设计链表复习1 {

    public static void main(String[] args) {
        a03_设计链表复习1 myLinkedList = new a03_设计链表复习1();
//        myLinkedList.addAtHead(1);
//        myLinkedList.addAtTail(3);
//        myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
//        myLinkedList.get(1);              // 返回 2
//        myLinkedList.deleteAtIndex(1);    // 现在，链表变为 1->3
//        myLinkedList.get(1);
        myLinkedList.addAtTail(1);
        myLinkedList.get(0);

    }

//    private static void print(a03_设计链表 myLinkedList) {
//        ListNode dummy=myLinkedList.dummy;
//        ListNode temp = dummy.next;
//        while (temp != null){
//            System.out.println(temp.val);
//            temp = temp.next;
//        }
//    }

    private ListNode dummyNode;
    private int size;

    public a03_设计链表复习1() {
        this.dummyNode = new ListNode(0);
        this.size = 0;
    }

    //从0开始，下标无效返回-1
    public int get(int index) {
        if(index < 0 || index >= size){
            return -1;
        }
        //定义临时变量
        ListNode currentNode = dummyNode.next;
        while (index > 0) {//如果index=0，就不应该进入循环
            currentNode = currentNode.next;
            index--;
        }
        return currentNode.val;
    }

    public void addAtHead(int val) {
        ListNode newNode = new ListNode(val);

        newNode.next = dummyNode.next;
        dummyNode.next = newNode;
        size++;
    }

    public void addAtTail(int val) {
        //定义临时变量
        ListNode currentNode = dummyNode;
        while (currentNode != null && currentNode.next != null) {
            currentNode = currentNode.next;
        }

        ListNode newNode = new ListNode(val);
        newNode.next = currentNode.next;
        currentNode.next = newNode;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size){
            return;
        }

        //定义临时变量
        ListNode currentNode = dummyNode;
        while (index > 0) {//遍历到index得上一个就停止了，如果是index=0，那么就不需要遍历
            currentNode = currentNode.next;
            index--;
        }

        ListNode newNode = new ListNode(val);
        newNode.next = currentNode.next;
        currentNode.next = newNode;
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size){
            return;
        }

        //定义临时变量
        ListNode currentNode = dummyNode;
        while (index > 0) {//遍历到index得上一个就停止了，如果是index=0，那么就不需要遍历
            currentNode = currentNode.next;
            index--;
        }

        currentNode.next = currentNode.next.next;
        size--;
    }
}
